<template>
	<view>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},
		onLoad(e) {
			const that = this
			if (!this.isWechat()){
				uni.showModal({
				    title: '提示',
				    content: '请在微信浏览器里面打开',
				    success: function (res) {
				        that.$myRouter.push({name:'index/index'})
				    }
				});
				return
			}
			uni.showLoading({
			    title: '加载中'
			});
		    let code = this.getUrlCode('code')
		    console.log(code)
		    if(code !== null || code !== "") {
		        this.wxAuthorize(code)
		    }
		},
		methods: {
			getUrlCode (name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
			},
			isWechat(){
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			wxAuthorize(code) {
				const that = this
			    if (code) {  
					that.$api.member.wechatBind({code:code}).then(res => {
						uni.hideLoading()
						setTimeout(function() {
							that.$u.toast('绑定成功')
							setTimeout(function() {
								that.$myRouter.back(2)
							}, 1500);
						}, 500);
					}).catch(err => {
						uni.hideLoading()
						setTimeout(function() {
							that.$u.toast(err.message)
						}, 500);
					})
			    }else {
					that.$api.home.wechatInfo({uri:encodeURIComponent(window.location.href)}).then(res => {
						// let appid = res.appid;
						//1.使用encodeURIComponent以及JSON.stringify()方法对对象进行字符串化和编码，这样可以控制url参数的长度，参考示例代码（uni-app书写方式，微信小程序自己改。）  
						// let uri = encodeURIComponent(window.location.href);  
						//2.接受信息的页面使用JSON.parse()以及decodeURIComponent()接收和解码参数。    
						//snsapi_base   //snsapi_base    scope = snsapi_base（不弹出授权页面，直接跳转，只能获取用户 openid ）。  
						//snsapi_userinfo  弹出  
						// let scope = res.scope;
						// let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=${scope}&state=123#wechat_redirect`;  
						//window.location.href = authURL;
						window.location.href = res.url;
					}).catch(err => {
						uni.hideLoading()
						setTimeout(function() {
							that.$u.toast(err.message)
						}, 500);
					})
			    }  
			}
		}
	}
</script>

<style>

</style>
